package com.jilian.powerstation.modul.fragment;


import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jilian.powerstation.Constant;
import com.jilian.powerstation.MyApplication;
import com.jilian.powerstation.R;
import com.jilian.powerstation.base.BaseDto;
import com.jilian.powerstation.base.BaseFragment;
import com.jilian.powerstation.common.dto.PowerDto;
import com.jilian.powerstation.common.dto.PowerInfoDetailDto;
import com.jilian.powerstation.manege.Weather.WeaterManager;
import com.jilian.powerstation.manege.Weather.WeatherInfo;
import com.jilian.powerstation.modul.activity.MainActivity;
import com.jilian.powerstation.modul.activity.WeatherActivity;
import com.jilian.powerstation.modul.viewmodel.UserViewModel;
import com.jilian.powerstation.utils.EmptyUtils;
import com.jilian.powerstation.utils.ProUtils;
import com.jilian.powerstation.utils.StatusBarUtil;
import com.jilian.powerstation.utils.ToastUitl;
import com.jilian.powerstation.utils.Utils;
import com.jilian.powerstation.views.IMainView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.socialize.UMShareAPI;

import interfaces.heweather.com.interfacesmodule.bean.Lang;
import interfaces.heweather.com.interfacesmodule.bean.Unit;
import interfaces.heweather.com.interfacesmodule.bean.search.Search;
import interfaces.heweather.com.interfacesmodule.bean.weather.forecast.Forecast;
import interfaces.heweather.com.interfacesmodule.bean.weather.forecast.ForecastBase;
import interfaces.heweather.com.interfacesmodule.bean.weather.now.Now;
import interfaces.heweather.com.interfacesmodule.view.HeWeather;


public class OneFragment extends BaseFragment implements BDLocationListener {

    private UserViewModel userViewModel;

    private MainActivity activity;
    private SmartRefreshLayout srHasData;

    private ImageView ivWether;
    private TextView tvWeatherStatus;
    private TextView tvWeatherTmp;
    private TextView tvPowerValue1;
    private TextView tvPowerValue2;
    private TextView tvPowerValue3;
    private TextView tvPowerValue4;
    private TextView tvPowerValue5;
    private TextView tvPowerValue6;
    private ImageView imgPower3;
    private ImageView imgPower4;
    private ImageView imgPower7;
    private ImageView imgPower8;
    private ScrollView scrollView;

    private LinearLayout llCurrWeater;

    private LinearLayout ll01Reverse;
    private TextView tvNumber1Reverse;
    private LinearLayout ll01Positive;
    private TextView tvNumber1;
    private LinearLayout ll02Reverse;
    private TextView tvNumber2Reverse;
    private LinearLayout ll02Positive;
    private TextView tvNumber2;
    private TextView tvUtil2;
    private LinearLayout ll03Reverse;
    private TextView tvNumber3Reverse;
    private LinearLayout ll03Positive;
    private TextView tvNumber3;
    private LinearLayout ll04Reverse;
    private TextView tvNumber4Reverse;
    private LinearLayout ll04Positive;
    private TextView tvNumber4;
    private LinearLayout ll05Reverse;
    private TextView tvNumber5Reverse;
    private LinearLayout ll05Positive;
    private TextView tvNumber5;
    private LinearLayout ll06Reverse;
    private TextView tvNumber6Reverse;
    private LinearLayout ll06Positive;
    private TextView tvNumber6;
    private RelativeLayout rl01;
    private RelativeLayout rl02;
    private RelativeLayout rl03;
    private RelativeLayout rl04;
    private RelativeLayout rl05;
    private RelativeLayout rl06;

    private IMainView mViewMain6;
    private IMainView mViewMain4;
    private IMainView mViewMain1;
    private IMainView mViewMain2;
    private IMainView mViewMain3;
    private IMainView mViewMain5;

    private ImageView img_station_3;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (mVisibleToUser) {
                getPowerInfo();
            }
            handler.postDelayed(this, Constant.FINALVALUE.FREASH_ON_TIME);
        }
    };


    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    boolean falg = false;

    @Override
    protected void loadData() {
        StatusBarUtil.setStatusBarMode(getmActivity(), true, R.color.white);
    }

    public void initDataAtFirstVisibleToUser(boolean isVisibleToUser) {

    }


    @Override
    protected void createViewModel() {
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_one;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        activity = (MainActivity) getmActivity();
        mViewMain6 = view.findViewById(R.id.view_main_6);
        mViewMain4 = view.findViewById(R.id.view_main_4);
        mViewMain1 = view.findViewById(R.id.view_main_1);
        mViewMain2 = view.findViewById(R.id.view_main_2);
        mViewMain3 = view.findViewById(R.id.view_main_3);
        mViewMain5 = view.findViewById(R.id.view_main_5);

        rl01 = (RelativeLayout) view.findViewById(R.id.rl_01);
        rl02 = (RelativeLayout) view.findViewById(R.id.rl_02);
        rl03 = (RelativeLayout) view.findViewById(R.id.rl_03);
        rl04 = (RelativeLayout) view.findViewById(R.id.rl_04);
        rl05 = (RelativeLayout) view.findViewById(R.id.rl_05);
        rl06 = (RelativeLayout) view.findViewById(R.id.rl_06);

        llCurrWeater = (LinearLayout) view.findViewById(R.id.ll_curr_weather);

        ll01Reverse = (LinearLayout) view.findViewById(R.id.ll_01_reverse);
        tvNumber1Reverse = (TextView) view.findViewById(R.id.tv_number_1_reverse);
        ll01Positive = (LinearLayout) view.findViewById(R.id.ll_01_positive);
        tvNumber1 = (TextView) view.findViewById(R.id.tv_number_1);
        ll02Reverse = (LinearLayout) view.findViewById(R.id.ll_02_reverse);
        tvNumber2Reverse = (TextView) view.findViewById(R.id.tv_number_2_reverse);
        ll02Positive = (LinearLayout) view.findViewById(R.id.ll_02_positive);
        tvNumber2 = (TextView) view.findViewById(R.id.tv_number_2);
        tvUtil2 = (TextView) view.findViewById(R.id.tv_util_2);
        ll03Reverse = (LinearLayout) view.findViewById(R.id.ll_03_reverse);
        tvNumber3Reverse = (TextView) view.findViewById(R.id.tv_number_3_reverse);
        ll03Positive = (LinearLayout) view.findViewById(R.id.ll_03_positive);
        tvNumber3 = (TextView) view.findViewById(R.id.tv_number_3);
        ll04Reverse = (LinearLayout) view.findViewById(R.id.ll_04_reverse);
        tvNumber4Reverse = (TextView) view.findViewById(R.id.tv_number_4_reverse);
        ll04Positive = (LinearLayout) view.findViewById(R.id.ll_04_positive);
        tvNumber4 = (TextView) view.findViewById(R.id.tv_number_4);
        ll05Reverse = (LinearLayout) view.findViewById(R.id.ll_05_reverse);
        tvNumber5Reverse = (TextView) view.findViewById(R.id.tv_number_5_reverse);
        ll05Positive = (LinearLayout) view.findViewById(R.id.ll_05_positive);
        tvNumber5 = (TextView) view.findViewById(R.id.tv_number_5);
        ll06Reverse = (LinearLayout) view.findViewById(R.id.ll_06_reverse);
        tvNumber6Reverse = (TextView) view.findViewById(R.id.tv_number_6_reverse);
        ll06Positive = (LinearLayout) view.findViewById(R.id.ll_06_positive);
        tvNumber6 = (TextView) view.findViewById(R.id.tv_number_6);

        scrollView = (ScrollView) view.findViewById(R.id.scrollView);
        tvPowerValue1 = (TextView) view.findViewById(R.id.tv_power_value1);
        tvPowerValue2 = (TextView) view.findViewById(R.id.tv_power_value2);
        tvPowerValue3 = (TextView) view.findViewById(R.id.tv_power_value3);
        tvPowerValue4 = (TextView) view.findViewById(R.id.tv_power_value4);
        tvPowerValue5 = (TextView) view.findViewById(R.id.tv_power_value5);
        tvPowerValue6 = (TextView) view.findViewById(R.id.tv_power_value6);

        imgPower3 = view.findViewById(R.id.img_station_5);
        imgPower4 = view.findViewById(R.id.img_station_8);
        imgPower7 = view.findViewById(R.id.img_station_3);
        imgPower8 = view.findViewById(R.id.img_station_1);

        srHasData = (SmartRefreshLayout) view.findViewById(R.id.sr_has_data);
        srHasData.setEnableLoadMore(false);
        ivWether = (ImageView) view.findViewById(R.id.iv_wether);
        tvWeatherStatus = (TextView) view.findViewById(R.id.tv_weather_status);
        tvWeatherTmp = (TextView) view.findViewById(R.id.tv_weather_tmp);
        setrightImageOne(R.drawable.image_right_one, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity) getActivity()).showShareDialog(scrollView, null, null, null);
            }
        });

        seNoBackTitle(activity.getData().getProductName(), v -> getActivity().finish());
        srHasData.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getPowerInfo();
            }
        });

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(getmActivity()).onActivityResult(requestCode, resultCode, data);
    }

    private String nowTmp;
    private String location;
    private String language;
    private ImageView ivBack;
    private String condCode;


    private boolean b_01 = true, b_02 = true, b_03 = true, b_04 = true, b_05 = true, b_06 = true;
    private Lang lang;
    private Unit unit;
    private PowerDto mPowerDto;

    @Override
    protected void initData() {
        handler.post(runnable);
        lang = Lang.ENGLISH;
        unit = Unit.METRIC;
        startLocationCilent();
        mPowerDto = (PowerDto) getActivity().getIntent().getSerializableExtra("data");
        getWeater(mPowerDto.getLatitude(), mPowerDto.getLongitude());
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
    }

    @Override
    protected void initListener() {
        setAnimators(); // 设置动画
        //  setCameraDistance(); // 设置镜头距离
        llCurrWeater.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WeatherActivity.class);
                intent.putExtra("data", mPowerDto);
                startActivity(intent);
            }
        });

        rl01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll01Reverse.setVisibility(View.VISIBLE);
                if (b_01) {
                    flipCard(ll01Positive, ll01Reverse, false);
                } else {
                    flipCard(ll01Positive, ll01Reverse, true);
                }
                b_01 = !b_01;
            }
        });


        rl02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll02Reverse.setVisibility(View.VISIBLE);
                if(b_02){
                    flipCard(ll02Positive,ll02Reverse,false);
                }
                else{
                    flipCard(ll02Positive,ll02Reverse,true);
                }
                b_02 =!b_02;
            }
        });


        rl03.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll03Reverse.setVisibility(View.VISIBLE);
                if (b_03) {
                    flipCard(ll03Positive, ll03Reverse, false);
                } else {
                    flipCard(ll03Positive, ll03Reverse, true);
                }
                b_03 = !b_03;
            }
        });


        rl04.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll04Reverse.setVisibility(View.VISIBLE);
                if (b_04) {
                    flipCard(ll04Positive, ll04Reverse, false);
                } else {
                    flipCard(ll04Positive, ll04Reverse, true);
                }
                b_04 = !b_04;
            }
        });
    }

    private AnimatorSet mRightOutSet;
    private AnimatorSet mLeftInSet;

    // 设置动画
    private void setAnimators() {
        mRightOutSet = (AnimatorSet) AnimatorInflater.loadAnimator(getmActivity(), R.animator.anim_out);
        mLeftInSet = (AnimatorSet) AnimatorInflater.loadAnimator(getmActivity(), R.animator.anim_in);

        // 设置点击事件
        mRightOutSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                rl01.setClickable(false);
                rl02.setClickable(false);
                rl03.setClickable(false);
                rl04.setClickable(false);
                rl05.setClickable(false);
                rl06.setClickable(false);

            }
        });
        mLeftInSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                rl01.setClickable(true);
                rl02.setClickable(true);
                rl03.setClickable(true);
                rl04.setClickable(true);
                rl05.setClickable(true);
                rl06.setClickable(true);
            }
        });
    }


    // 翻转卡片
    public void flipCard(LinearLayout positive, LinearLayout reverse, boolean mIsShowBack) {

        // 正面朝上
        if (!mIsShowBack) {
            mRightOutSet.setTarget(positive);
            mLeftInSet.setTarget(reverse);

            mRightOutSet.start();
            mLeftInSet.start();

        } else { // 背面朝上
            mRightOutSet.setTarget(reverse);
            mLeftInSet.setTarget(positive);
            mRightOutSet.start();
            mLeftInSet.start();

        }

    }

    /**
     * 获取电站详情
     */
    private void getPowerInfo() {
        userViewModel.getPowerInfo(getActivity().getIntent().getStringExtra("sn"));
        userViewModel.getPowerliveData().observe(this, new Observer<BaseDto<PowerInfoDetailDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<PowerInfoDetailDto> detailDtoBaseDto) {
                srHasData.finishRefresh();
                if (detailDtoBaseDto.isSuccess()) {
                    if (EmptyUtils.isNotEmpty(detailDtoBaseDto)) {
                        if (!detailDtoBaseDto.getData().isOnLine()) {

                            //离线状态
                            handler.removeCallbacks(runnable);
                            initDetailView(new PowerInfoDetailDto());
                        } else {
                            //在线
                            initDetailView(detailDtoBaseDto.getData());
                        }
                    }
                } else {
                    ToastUitl.showImageToastTips(detailDtoBaseDto.getMsg());
                }
            }
        });
    }

    /**
     * 初始化電站詳情视图
     *
     * @param data
     */
    private void initDetailView(PowerInfoDetailDto data) {
        Log.e(TAG, "initDetailView: " + data.toString());
        tvNumber1.setText(ProUtils.getValueOneStr(data.getToday_own_consumption_rate(), 0.1F));//当日自发自用率
        tvNumber2.setText(ProUtils.getValueStr(data.getTotalEquipment()));//设备运行数量(没字段，感觉)
        tvNumber3.setText(ProUtils.getValueStr(data.getToday_pv_production()));//当天发电量
        tvNumber4.setText(ProUtils.getValueStr(data.getToday_consumption()));//当天用电
        tvNumber5.setText(ProUtils.getValueStr(data.getHistory_estimated_refund()));
        tvNumber6.setText(ProUtils.getValueStr(data.getHistory_carbon_offset()));

        tvNumber1Reverse.setText(ProUtils.getValueStr(data.getToday_own_consumption()));//
        tvNumber3Reverse.setText(ProUtils.getValueOneStr(data.getHistory_pv_production(), 0.1F));//总发电
        tvNumber4Reverse.setText(ProUtils.getValueOneStr(data.getHistory_consumption(), 0.1F));//总用电




        setPowerView(data.getPv2GRID(), tvPowerValue1, mViewMain1, 1);
        setPowerView(data.getPv2BAT(), tvPowerValue2, mViewMain2, 0);
        setPowerView(data.getBat2GRID(), tvPowerValue3, mViewMain3);
        setPowerView(data.getPv2LOAD(), tvPowerValue4, mViewMain4, 1);
        setPowerView(data.getBat2LOAD(), tvPowerValue5, mViewMain5, 0);
        setPowerView(data.getGrid2LOAD(), tvPowerValue6, mViewMain6, 0);

        if (!TextUtils.isEmpty(data.getBatteryStatus())) {
            int valueInt = Utils.parseInt(data.getBatteryStatus());
            if (valueInt == 0) {//空闲
                imgPower7.setImageResource(R.drawable.image_station_3_0);
            } else if (valueInt == 1) {//充电
                imgPower7.setImageResource(R.drawable.image_station_3_2);
            } else if (valueInt == 2) {//放电
                imgPower7.setImageResource(R.drawable.image_station_3_3);
            } else if (valueInt == 3) {//低電量
                imgPower7.setImageResource(R.drawable.image_station_3_1);
            }
        }


        if (data.getLoad_a_active_power() <= 0) {
            imgPower8.setImageResource(R.drawable.image_station_1_0);
        } else {
            imgPower8.setImageResource(R.drawable.image_station_1);
        }
    }

    /**
     * @param textView
     * @param mViewMain
     * @param status
     */
    public void setPowerView(String value, TextView textView, IMainView mViewMain, int status) {
        if (!TextUtils.isEmpty(value)) {
            int intValue = Utils.parseInt(value);
            if (intValue <= 0) {
                mViewMain.setStatus(2);
                textView.setText("0 W");
            } else {
                mViewMain.setStatus(status);
                textView.setText(intValue + " W");
            }
        } else {
            mViewMain.setStatus(2);
            textView.setText("- W");
        }

    }

    /**
     * @param textView
     * @param mViewMain
     */
    public void setPowerView(String value, TextView textView, IMainView mViewMain) {
        if (!TextUtils.isEmpty(value)) {
            int intValue = Utils.parseInt(value);
            if (intValue < 0) {
                mViewMain.setStatus(1);
                textView.setText(value + " W");
            } else if (intValue == 0) {
                mViewMain.setStatus(2);
                textView.setText("0 W");
            } else {
                mViewMain.setStatus(0);
                textView.setText(value + " W");
            }

        } else {
            mViewMain.setStatus(2);
            textView.setText("- W");
        }
    }

    private int getIntValue(String value) {
        if (value == null) return 0;
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            return 0;
        }

    }


    /**
     * 开启定位
     */
    private void startLocationCilent() {
        // 申请权限
        MyApplication.getInstance().mLocationClient.start();
        MyApplication.getInstance().mLocationClient.registerLocationListener(this);
    }

    private void getWeater(double currentLat, double currentLon) {
        if (mVisibleToUser) {
            weaterManager.getWeather("https://api.openweathermap.org/data/2.5/weather", currentLat, currentLon, new WeaterManager.HttpCallBack<String>() {
                @Override
                public void onSuccess(String o) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!TextUtils.isEmpty(o)) {
                                WeatherInfo info = null;
                                try {
                                    info = new Gson().fromJson(o, WeatherInfo.class);
                                } catch (Exception e) {
                                    return;
                                }

                                tvWeatherTmp.setText((int)info.getMain().getTemp_min() + "～" + (int)info.getMain().getTemp_max() + "°C");
                                if (info.getWeather() != null && info.getWeather().size() > 0) {
                                    WeatherInfo.WeatherBean weatherBean = info.getWeather().get(0);
                                    tvWeatherStatus.setText(weatherBean.getMain());
                                    Glide.with(getActivity()).
                                            load(String.format("https://openweathermap.org/img/w/%s.png", weatherBean.getIcon()))
                                            .into(ivWether);//
                                }


                            }
                        }
                    });

                }

                @Override
                public void onError(Exception e) {
                }
            });
        }

    }

    private double currentLat;//当前位置的维度
    private double currentLon;//当前位置的维度

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation != null) {
            currentLat = bdLocation.getLatitude();
            currentLon = bdLocation.getLongitude();
//            getWeatherGridNow(currentLon + "," + currentLat);
            MyApplication.getInstance().mLocationClient.stop();

        }
    }

    WeaterManager weaterManager = new WeaterManager();

}
